package com.neo.subscribe;

import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SeleniumUtils {

    /**
     * chromedriver 地址
     */
    public static final String CHROME_DRIVER_PATH = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe";
    /**
     * 爬取的根目录
     */
    public static final String ROOT_URL = "https://mall.11185.cn/web/jyIndex?businessId=JY&channel=PC";

    public static final String REGEX = "https://mall.11185.cn/web/shopWindow\\?cateId=(\\d+)";

    public static WebDriver driver;

    public static Set<String> openRoot() {
        try {
            System.setProperty("webdriver.chrome.driver", CHROME_DRIVER_PATH);
            ChromeOptions options = new ChromeOptions();
            options.setExperimentalOption("prefs", ImmutableMap.of("profile.managed_default_content_settings.images", 2));
            driver = new ChromeDriver();
            driver.get(ROOT_URL);
            String pageSource = driver.getPageSource();
            return getCateIds(pageSource, REGEX);
        } finally {
            if (driver != null) {
                driver.quit();
            }
        }
    }

    public static Set<String> getCateIds(String html, String regex) {
        Set<String> result = new HashSet<>();
        Pattern pattern = Pattern.compile(regex);
        // 利用正则去匹配
        Matcher matcher = pattern.matcher(html);
        while (matcher.find()) {
            String cateId = matcher.group(1);
            if (StringUtils.isNoneBlank(cateId)) {
                result.add(cateId);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        openRoot();
    }
}
